//
//  SubscribeViewController.m
//  项目A_百思不得姐
//
//  Created by wudongyang on 16/5/16.
//  Copyright © 2016年 wudongyang. All rights reserved.
//

#import "SubscribeViewController.h"
#import "RecommendViewController.h"
#import "SubscribeTableViewCell.h"
#import <AFNetworking.h>
#import "SubscribeModel.h"
#import "LandingViewController.h"
@interface SubscribeViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating>
@property(nonatomic, strong)UITableView *myTableView;
@property(nonatomic, strong)NSMutableArray *AllArray;
@property(nonatomic, strong)NSMutableArray *searchArray;
@property(nonatomic, strong)UISearchBar *mySearchBar;
@property(nonatomic, strong)UISearchController *searchController;

@end

@implementation SubscribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.AllArray = [NSMutableArray array];
    self.searchArray = [NSMutableArray array];
    [self getData];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = @"搜索标签";
    // 设置导航栏内容
    // 给导航栏标题添加图片(百思不得姐)
    self.navigationItem.title = @"订阅";

    // 创建 关注按钮(点击进入推荐关注) 将按钮加入到导航栏左按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"friendsRecommentIcon" highImage:@"friendsRecommentIcon-click" target:self action:@selector(leftButtonAction)];
    // 设置背景色
    self.view.backgroundColor = DSRGBA(223, 223, 223, 1);
    // 创建tableView
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[SubscribeTableViewCell class] forCellReuseIdentifier:@"reuse"];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    
    
    
}
-(void)getData{
    //GET请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://d.api.budejie.com/tag/subscribe/bs0315-iphone-4.1.json?appname=bs0315&asid=986C8830-1671-4071-BB49-37A7E7F66615&client=iphone&device=ios%20device&from=ios&jbk=0&mac=&market=&openudid=21c4a1f4b37d431985e8e05255fdfec2bcb43c5a&udid=&ver=4.1" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        NSMutableArray *array = [responseObject objectForKey:@"rec_tags"];
        for (NSMutableDictionary *dic in array) {
            SubscribeModel *subModel = [[SubscribeModel alloc] init];
            [subModel setValuesForKeysWithDictionary:dic];
            [self.AllArray addObject:subModel];
            
        }
        [self.myTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
        
    }];
    


}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return self.searchArray.count;
    }
    else{
        return self.AllArray.count;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.myTableView.rowHeight = 80;
    SubscribeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[SubscribeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
    }
    if (self.searchController.active) {
        SubscribeModel *model = [self.searchArray objectAtIndex:indexPath.row];
        cell.subModel = model;
    }
    else{
        SubscribeModel *model = [self.AllArray objectAtIndex:indexPath.row];
        cell.subModel = model;
    
    }
    
    // 订阅按钮Block回调点击方法
    cell.SubscribeBlock = ^(UIButton *button){
        // 在云里取出isLogin的字符串值
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSString *isLogin = [defaults objectForKey:@"isLogin"];
        // 如果未登入状态下点击弹出登入框
            if ([isLogin isEqualToString:@"0"]) {
                LandingViewController *LandingVC = [[LandingViewController alloc] init];
                [self presentViewController:LandingVC animated:YES completion:nil];
        
            }else{
                [button setTitle:@"已订" forState:UIControlStateNormal];
            
            }
        
        
    };
    
    
    
    
    cell.selectionStyle = 0;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DSLog(@"订阅cell的点击方法");
    SubscribeModel *model = nil;
    if (self.searchController.active) {
        NSLog(@"选中搜索列表");
        model = [self.searchArray objectAtIndex:indexPath.row];
    }
    else{
        NSLog(@"选中所有列表");
        model = [self.AllArray objectAtIndex:indexPath.row];
    }

}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
    NSLog(@"===%@",searchString);
    
    [self.searchArray removeAllObjects];
    for (SubscribeModel *model in self.AllArray) {
        
        //rangeOfString:方法是在movieName中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([model.theme_name rangeOfString:searchString].location != NSNotFound) {
            
            [self.searchArray addObject:model];
        }
    }
    NSLog(@"searchArray===%@",self.searchArray);
    
    [self.myTableView reloadData];
    
}
//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.searchController.active) {
        
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
        
    }
}

// 左按钮点击方法
-(void)leftButtonAction{
    
    DSLog(@"点击进入推荐关注,我在SubscribeViewController左按钮点击方法");
    RecommendViewController *RecommendVC = [[RecommendViewController alloc] init];
    [self.navigationController pushViewController:RecommendVC animated:YES];
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
